package com.evola.conditionalformatting
{
	import mx.collections.ICollectionView;

	public class ViewCondition
	{

		public var operator:String;
		public var leftValue:ViewValue;
		public var viewFunction:ViewFunction;
		public var rightValue:ViewValue;

		public function ViewCondition(leftField:ViewValue, func:ViewFunction, rightField:ViewValue, operator:String)
		{
			this.leftValue=leftField;
			this.viewFunction=func;
			this.rightValue=rightField;
			this.operator=operator;
		}

		public function doesAccept(value:Object, dataProvider : ICollectionView):Boolean
		{

			//radimo resolve vrednosti pre nego sto izvrsimo funkciju
			var realLeftValue:Object=leftValue.getRealValue(value);
			var realRightValue:Object=rightValue.getRealValue(value);

			//sada imamo dve promenjive od kojih je jedna sigurno odgovarajuceg tipa
			//ali druga ne mora da bude, moramo da ih prebacimo na isti tip
			//uzimamo tip od one koja nije null i nije string
			var valueToTake:Object;

			if (realLeftValue && !(realLeftValue is String))
			{

				valueToTake=realLeftValue;
			}
			else
			{

				valueToTake=realRightValue;

				//osim ako nam je desna strana zapravo null
				if (!valueToTake)
					valueToTake=realLeftValue;
			}

			//ako nam je validna vrendost NaN to je isto sto i null za domen brojeva, moramo da nastavimo sa brojevima
			if (valueToTake is Number || isNaN(valueToTake as Number))
			{

				realLeftValue=Number(realLeftValue);
				realRightValue=Number(realRightValue);
			}
			else if (valueToTake is Boolean)
			{

				realLeftValue=realLeftValue is Boolean ? realLeftValue : realLeftValue ? realLeftValue == "true" : false;
				realRightValue=realRightValue is Boolean ? realRightValue : realRightValue ? realRightValue == "true" : false;
			}
			else if (valueToTake is Date)
			{

				realLeftValue=realLeftValue is Date ? realLeftValue : realLeftValue ? Utils.stringToDate(String(realLeftValue)) : null;
				realRightValue=realRightValue is Date ? realRightValue : realRightValue ? Utils.stringToDate(String(realRightValue)) : null;
			}
			else
			{

				realLeftValue=String(realLeftValue);
				realRightValue=String(realRightValue);
			}

			return viewFunction.execute(realLeftValue, realRightValue, dataProvider, leftValue, rightValue);
		}

		public function toExpressionString():String
		{

			var exp:String="";

			if (operator)
				exp+=operator;

			exp+=leftValue.toExpressionString() + viewFunction.toExpressionString() + rightValue.toExpressionString();

			return exp;
		}

	}
}
